import { Component, OnInit } from '@angular/core';
import { NbAuthJWTToken, NbAuthService } from '@nebular/auth';
import { NbMenuService } from '@nebular/theme';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { filter, map, takeUntil } from 'rxjs/operators';

import { UserData } from '../../@core/data/users';

@Component({
  selector: 'ngx-users',
  templateUrl: './user.component.html'
})
export class UserComponent implements OnInit {

  private destroy$: Subject<void> = new Subject<void>();
  userPictureOnly: boolean = false;
  user: any;

  userMenu = [ { title: 'Log out' } ];

  constructor(
    private userService: UserData,
    private authService: NbAuthService,
    private menuService: NbMenuService,
    private router: Router) { }

  ngOnInit(): void {
    this.userService.getUsers()
        .pipe(takeUntil(this.destroy$))
        .subscribe((users: any) => this.user = users.alan);

    this.menuService.onItemClick()
        .pipe(
          filter(({tag}) => tag === 'header-menu'),
          map(({ item: { title } }) => title),
        )
        .subscribe(title => {
          // 退出按钮移除 token 并返回到登录页
          this.authService.logout('password');
          localStorage.removeItem('auth_app_token');
          sessionStorage.removeItem('auth_app_token');
          this.router.navigate(['/auth']);
        })
  }

}
